package com.worklog.controller;

import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.worklog.model.User;
import com.worklog.model.UserRole;
import com.worklog.service.UserRoleService;
import com.worklog.service.UserService;
import com.worklog.util.ExportBeanExcel;
import com.worklog.util.PasswordHelper;
import com.worklog.util.ResultData;
import com.worklog.util.ResultMap;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/users")
public class UserController {
	@Resource
	private UserService userService;
	@Resource
	private UserRoleService userRoleService;

	@RequestMapping
	public ResultData getAll(User user, @RequestParam(required = false, defaultValue = "1") int start,
			@RequestParam(required = false, defaultValue = "10") int length) {
		ResultData result = new ResultData();
		try {
			PageInfo<User> pageInfo = userService.selectByPage(user, start, length);
			result.setData(pageInfo.getList());
			result.setTotal(pageInfo.getTotal());
			result.success("查询所有用户信息成功！");
		} catch (Exception e) {
			log.info(e.getMessage(), e);
			result.error("查询所有用户信息失败！");
		}
		return result;
	}

	/**
	 * 保存用户角色
	 * 
	 * @param userRole 用户角色 此处获取的参数的角色id是以 “,” 分隔的字符串
	 * @return
	 */
	@RequestMapping("/saveUserRoles")
	public String saveUserRoles(UserRole userRole) {
		if (StringUtils.isEmpty(userRole.getUserid()))
			return "error";
		try {
			userRoleService.addUserRole(userRole);
			return "success";
		} catch (Exception e) {
			log.info(e.getMessage(), e);
			return "fail";
		}
	}

	@RequestMapping(value = "/add")
	public ResultData add(User user) {
		ResultData result = new ResultData();

		try {
			User u = userService.selectByUsername(user.getUsername());
			if (u != null) {
				result.error("用户名已存在!", null);
				return result;
			}
			user.setEnable(1);
			PasswordHelper passwordHelper = new PasswordHelper();
			passwordHelper.encryptPassword(user);
			user.setCreateTime(new Timestamp(System.currentTimeMillis()));
			user.setUpdateTime(new Timestamp(System.currentTimeMillis()));
			userService.save(user);
			result.success("新增用户成功");
		} catch (Exception e) {
			log.info(e.getMessage(), e);
			result.error("新增用户失败");
		}
		return result;
	}

	@RequestMapping(value = "/delete")
	public ResultData delete(@RequestParam(value = "id", required = true) Integer id) {
		ResultData result = new ResultData();
		try {
			if (id == 1) {
				result.error("该用户不可删除");
				return result;
			}
			userService.delUser(id);
			result.success("删除成功");
		} catch (Exception e) {
			log.info("删除失败" + e.getMessage(), e);
			result.error("删除失败");
		}
		return result;
	}

	@RequestMapping(value = "/deleteUser")
	public ResultData deleteUser(@RequestBody Integer[] ids) {
		ResultData result = new ResultData();
		List<Integer> idList = Arrays.asList(ids);
		try {
			if (idList.contains(1)) {
				result.error("该用户不可删除");
				return result;
			}
			userService.delUsers(idList);
			result.success("删除成功");
		} catch (Exception e) {
			log.info(e.getMessage(), e);
			result.error("删除失败");
		}
		return result;
	}

	@RequestMapping(value = "/update")
	public ResultData update(User user) {
		ResultData result = new ResultData();
		try {
			User u = userService.selectByUsername(user.getUsername());
			Integer userId = user.getId();
			if (u != null && !userId.equals(u.getId())) {
				result.error("用户名已存在!", null);
				return result;
			}

			PasswordHelper passwordHelper = new PasswordHelper();
			passwordHelper.encryptPassword(user);
			user.setUpdateTime(new Timestamp(System.currentTimeMillis()));
			userService.updateNotNull(user);

			result.success("更新用户信息成功");
		} catch (Exception e) {
			log.info(e.getMessage(), e);
			result.error("更新用户信息失败");
		}
		return result;
	}

	@RequestMapping(value = "/queryAll")
	public ResultData queryAll(@RequestParam(required = false, defaultValue = "1") int page,
			@RequestParam(required = false, defaultValue = "10") int limit) {
		ResultData result = new ResultData();
		try {
			PageInfo<User> pageInfo = userService.queryAll(page, limit);
			result.setData(pageInfo.getList());
			result.setTotal(pageInfo.getTotal());
			result.success("查询所有用户信息成功！");
		} catch (Exception e) {
			log.info(e.getMessage(), e);
			result.error("查询所有用户信息失败！");
		}
		return result;
	}

	@RequestMapping(value = "/queryAllStatus")
	public ResultData queryAllStatus() {
		ResultData result = new ResultData();
		try {
			List<ResultMap<String, Object>> list = userService.queryAllStatus();
			result.setData(list);
			result.success("查询所有用户信息成功！");
		} catch (Exception e) {
			log.info(e.getMessage(), e);
			result.error("查询所有用户信息失败！");
		}
		return result;
	}

	@RequestMapping(value = "/export")
	public ResultData export(String headersName, String headersId) {
		ResultData result = new ResultData();
		List<String> names = JSON.parseArray(headersName, String.class);
		List<String> ids = JSON.parseArray(headersId, String.class);
		try {
			PageInfo<User> pageInfo = userService.selectByPage(new User(), 1, 10);
			List<User> users = pageInfo.getList();

			ExportBeanExcel<User> exportExcel = new ExportBeanExcel<User>();
			exportExcel.exportExcel("asd", names, ids, users);
			result.setData(users);
			result.success("查询所有用户信息成功！");
		} catch (Exception e) {
			log.info(e.getMessage(), e);
			result.error("查询所有用户信息失败！");
		}
		return result;
	}
}
